﻿using System;

namespace ExFlash.Records
{
    public class EncodedU32 : ISwfSerializable
    {
        private uint value;

        static public implicit operator uint(EncodedU32 enc)
        {
            return enc.value;
        }

        #region ISwfSerializable Members

        public void SwfDeserialize(BinaryBitReader reader)
        {
            uint result = reader.ReadByte();

            if ((result & 0x00000080) == 0)
            {
                value = result;
                return;
            }

            result = ((result & 0x0000007f) | (uint)(reader.ReadByte() << 7));
            
            if ((result & 0x00004000) == 0)
            {
                value = result;
                return;
            }

            result = ((result & 0x00003fff) | (uint)(reader.ReadByte() << 14));
            
            if ((result & 0x00200000) == 0)
            {
                value = result;
                return;
            }

            result = ((result & 0x001fffff) | (uint)(reader.ReadByte() << 21));
            
            if ((result & 0x10000000) == 0)
            {
                value = result;
                return;
            }

            result = ((result & 0x0fffffff) | (uint)(reader.ReadByte() << 28));
            value = result;
        }

        public void SwfSerialize(byte[] arr, ref int offset)
        {
            throw new NotImplementedException();
        }

        #endregion

        public override string ToString()
        {
            return value.ToString();
        }
    }
}
